﻿@*
    这个文件是客户管理的视图页面。
    我们使用 Layui 框架来构建一个功能丰富的表格，支持搜索、分页、增删改查等操作。
*@
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>客户管理</title>
    <link href="~/scripts/layui-v2.5.6/layui/css/layui.css" rel="stylesheet" />
    <style>
        .validation-msg {
            color: #FF5722 !important; 
            display: none; 
            line-height: 1; 
            margin-top: 2px; 
            font-size: 12px;
        }
    </style>
</head>
<body>
    <div class="layui-fluid">
        <div class="layui-card">
            <div class="layui-card-body">
                <!-- 搜索条件表单 -->
                <form class="layui-form" id="search-form">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">客户编码</label>
                            <div class="layui-input-inline">
                                <input type="text" name="customerCode" placeholder="请输入客户编码" autocomplete="off" class="layui-input">
                </div>
                </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">客户名称</label>
                            <div class="layui-input-inline">
                                <input type="text" name="customerName" placeholder="请输入客户名称" autocomplete="off" class="layui-input">
                </div>
            </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">客户简称</label>
                            <div class="layui-input-inline">
                                <input type="text" name="customerNiciname" placeholder="请输入客户简称" autocomplete="off" class="layui-input">
                            </div>
                </div>
                         <div class="layui-inline">
                            <label class="layui-form-label">是否启用</label>
                            <div class="layui-input-inline">
                                <select name="customerIsTrue">
                                    <option value="">全部</option>
                        <option value="true">是</option>
                        <option value="false">否</option>
                    </select>
                </div>
                        </div>
                        <div class="layui-inline">
                            <button class="layui-btn" lay-submit lay-filter="search-btn">
                                <i class="layui-icon layui-icon-search"></i>查询
                    </button>
                            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>
        </form>

                <!-- 表格上方的工具栏 -->
                <script type="text/html" id="toolbar">
                    <div class="layui-btn-container">
                        <button class="layui-btn layui-btn-sm" lay-event="add">
                            <i class="layui-icon layui-icon-add-1"></i>新增
        </button>
                        <button class="layui-btn layui-btn-sm layui-btn-danger" lay-event="delete">
                            <i class="layui-icon layui-icon-delete"></i>删除
        </button>
    </div>
                </script>

                <!-- 数据表格容器 -->
                <table id="customer-table" lay-filter="customer-table"></table>

                <!-- 表格中每一行的操作按钮 -->
                <script type="text/html" id="row-toolbar">
                    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
                    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete">删除</a>
                </script>

            </div>
        </div>
    </div>

    <!-- 新增/编辑弹窗的 HTML 结构 -->
    <div id="edit-dialog" style="display: none; padding: 20px;">
        <form class="layui-form" id="edit-form" lay-filter="edit-form">
            <input type="hidden" name="id">
            <div class="layui-form-item">
                <label class="layui-form-label">客户编码</label>
                <div class="layui-input-block">
                    <div class="layui-inline" style="width: 300px; vertical-align: top;">
                        <input type="text" name="customerCode" required placeholder="请输入或点右侧开关生成" autocomplete="off" class="layui-input">
                        <div class="validation-msg">客户编码不能为空</div>
                    </div>
                    <div class="layui-inline" style="vertical-align: middle;">
                        <input type="checkbox" id="auto-generate-code" lay-skin="switch" lay-text="ON|OFF" lay-filter="auto-generate-code">
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">客户名称</label>
                <div class="layui-input-block">
                    <input type="text" name="customerName" required placeholder="请输入客户名称" autocomplete="off" class="layui-input">
                     <div class="validation-msg">客户名称不能为空</div>
                </div>
            </div>
             <div class="layui-form-item">
                <label class="layui-form-label">客户简称</label>
                <div class="layui-input-block">
                    <input type="text" name="customerNiciname" placeholder="请输入客户简称" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">客户类型</label>
                <div class="layui-input-block">
                    <input type="text" name="customerType" placeholder="请输入客户类型" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">联系电话</label>
                <div class="layui-input-block">
                    <input type="text" name="customerPhone" placeholder="请输入联系电话" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">是否启用</label>
                <div class="layui-input-block">
                    <input type="radio" name="customerIsTrue" value="true" title="是" checked>
                    <input type="radio" name="customerIsTrue" value="false" title="否">
        </div>
            </div>
            <div class="layui-form-item" style="text-align: right;">
                <button class="layui-btn" lay-submit lay-filter="save-btn">保存</button>
                <button type="button" class="layui-btn layui-btn-primary" id="cancel-btn">取消</button>
        </div>
        </form>
    </div>

    <script src="~/scripts/jquery-3.4.1.min.js"></script>
    <script src="~/scripts/layui-v2.5.6/layui/layui.all.js"></script>
    <script>
        layui.use(['table', 'form', 'layer'], function () {
            var table = layui.table;
            var form = layui.form;
            var layer = layui.layer;
            var $ = layui.jquery;
            
            var currentEditId = 0;

            table.render({
                elem: '#customer-table',
                id: 'customerTable',
                url: '/Customer/api/list', 
                toolbar: '#toolbar',
                defaultToolbar: ['filter', 'exports', 'print'],
                page: true,
                request: {
                    pageName: 'skipCount',
                    limitName: 'maxResultCount'
                },
                parseData: function(res){
                    return {
                        "code": 0,
                        "msg": "",
                        "count": res.totalCount,
                        "data": res.items
                    };
                },
                cols: [[
                    { type: 'checkbox', fixed: 'left' },
                    { field: 'id', title: 'ID', hide: true },
                    { field: 'customerCode', title: '客户编码', width: 120, sort: true },
                    { field: 'customerName', title: '客户名称', width: 200, sort: true },
                    { field: 'customerNiciname', title: '客户简称', width: 150 },
                    { field: 'customerType', title: '客户类型', width: 120 },
                    { field: 'customerPhone', title: '客户电话', width: 120 },
                    { field: 'customerIsTrue', title: '是否启用', width: 100, templet: function (d) {
                        return d.customerIsTrue ? '<span class="layui-badge layui-bg-green">是</span>' : '<span class="layui-badge layui-bg-gray">否</span>';
                    }},
                    { fixed: 'right', title: '操作', toolbar: '#row-toolbar', width: 150 }
                ]],
                response: {
                    statusCode: 0
                }
            });

            form.on('submit(search-btn)', function (data) {
                table.reload('customerTable', {
                    where: data.field,
                    page: {
                        curr: 1
                    }
                });
                return false;
            });

            table.on('toolbar(customer-table)', function (obj) {
                var checkStatus = table.checkStatus(obj.config.id);
                switch (obj.event) {
                    case 'add':
                        openEditDialog('add');
                        break;
                    case 'delete':
                        var data = checkStatus.data;
                        if (data.length === 0) {
                            layer.msg('请选择要删除的行');
                        } else {
                            var ids = data.map(function(item) { return item.id; });
                            layer.confirm('确定删除选中的 ' + data.length + ' 条数据吗？', function (index) {
                                $.ajax({
                                    url: '/Customer/api/batch-delete',
                                    type: 'POST',
                                    contentType: 'application/json',
                                    data: JSON.stringify(ids),
                                    success: function() {
                                        layer.msg('删除成功');
                                        table.reload('customerTable');
                                    },
                                    error: function() {
                                        layer.msg('删除失败');
                                    }
                                });
                                layer.close(index);
                            });
                        }
                        break;
                };
            });

            table.on('tool(customer-table)', function (obj) {
                var data = obj.data;
                if (obj.event === 'delete') {
                    layer.confirm('确定删除这条数据吗？', function (index) {
                         $.ajax({
                            url: '/Customer/api/delete/' + data.id,
                            type: 'DELETE',
                            success: function() {
                                layer.msg('删除成功');
                                obj.del();
                            },
                            error: function() {
                                layer.msg('删除失败');
                            }
                        });
                        layer.close(index);
                    });
                } else if (obj.event === 'edit') {
                    openEditDialog('edit', data);
                }
            });
            
            form.on('switch(auto-generate-code)', function(data){
                var codeInput = $('#edit-form input[name="customerCode"]');
                if(data.elem.checked){
                    var timestamp = new Date().getTime();
                    var randomSuffix = Math.floor(Math.random() * 100);
                    var newCode = 'C' + timestamp + randomSuffix.toString().padStart(2, '0');
                    codeInput.val(newCode).prop('disabled', true);
                    codeInput.removeClass('layui-form-danger');
                    codeInput.siblings('.validation-msg').hide();
                } else {
                    codeInput.val('').prop('disabled', false);
                }
            });

            function openEditDialog(type, data) {
                var title = type === 'add' ? '新增客户' : '编辑客户';
                currentEditId = data ? data.id : 0;

                layer.open({
                    type: 1,
                    title: title,
                    area: ['600px', '580px'],
                    content: $('#edit-dialog'),
                    success: function () {
                        $('#edit-form')[0].reset();
                        $('.validation-msg').hide();
                        $('#edit-form .layui-input').removeClass('layui-form-danger');
                        
                        var codeInput = $('#edit-form input[name="customerCode"]');
                        var autoSwitch = $('#auto-generate-code');

                        if (type === 'edit') {
                            form.val('edit-form', data);
                            codeInput.prop('disabled', true);
                            autoSwitch.prop('checked', false).prop('disabled', true);
                        } else {
                            codeInput.prop('disabled', false);
                            autoSwitch.prop('checked', false).prop('disabled', false);
                        }
                        form.render();
                    }
                });
            }

            form.on('submit(save-btn)', function (data) {
                if (!validateForm()) {
                    return false; 
                }
                
                var formData = data.field;
                formData.customerIsTrue = formData.customerIsTrue === 'true';
                
                // If auto-generation was used, the input is disabled, so we need to get value directly
                if ($('#auto-generate-code').prop('checked')) {
                    formData.customerCode = $('#edit-form input[name="customerCode"]').val();
                }

                var url = currentEditId > 0 ? '/Customer/api/update/' + currentEditId : '/Customer/api/create';
                var type = currentEditId > 0 ? 'PUT' : 'POST';

                $.ajax({
                    url: url,
                    type: type,
                    contentType: 'application/json',
                    data: JSON.stringify(formData),
                    success: function (res) {
                        layer.closeAll('page');
                        layer.msg('保存成功');
                        table.reload('customerTable');
                        currentEditId = 0;
                    },
                    error: function () {
                        layer.msg('保存失败');
                    }
                });

                return false;
            });

            function validateForm() {
                var isValid = true;
                var formElement = $('#edit-form');
                
                // Restrict queries to the form
                formElement.find('.validation-msg').hide();
                formElement.find('.layui-form-danger').removeClass('layui-form-danger');

                var codeInput = formElement.find('input[name="customerCode"]');
                var isCodeInputDisabled = codeInput.prop('disabled');
                if (isCodeInputDisabled) {
                    codeInput.prop('disabled', false);
                }

                if (!codeInput.val()) {
                    codeInput.addClass('layui-form-danger').siblings('.validation-msg').show();
                    isValid = false;
                }

                if (isCodeInputDisabled) {
                    codeInput.prop('disabled', true);
                }

                var nameInput = formElement.find('input[name="customerName"]');
                if (!nameInput.val()) {
                    nameInput.addClass('layui-form-danger').siblings('.validation-msg').show();
                    isValid = false;
                }

                return isValid;
            }

            $('#cancel-btn').on('click', function() {
                layer.closeAll('page');
            });
        });
    </script>
</body>
</html>
